package com.tony.business.interceptor;

import com.alibaba.fastjson.JSON;
import com.tony.business.util.TokenUtil;
import com.tony.domain.bo.JsonResult;
import com.tony.domain.bo.UserInfo;
import com.tony.domain.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author x
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        log.debug("token={}", token);
        if (StringUtils.isEmpty(token)) {
            returnJson(response, new CustomException("token为空"));
            return false;
        }
        try {
            UserInfo userInfo = TokenUtil.getJWTBo(token);
            request.setAttribute("userInfo", userInfo);
        } catch (RuntimeException e) {
            returnJson(response, e);
            log.error("解析token出错：{}", e.getMessage());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {

    }

    private void returnJson(HttpServletResponse response, RuntimeException re) {
        JsonResult<?> jsonResult = new JsonResult<>(re);
        String jsonString = JSON.toJSONString(jsonResult);
        log.info(jsonString);
        response.setCharacterEncoding("UTF-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try (PrintWriter writer = response.getWriter()) {
            writer.print(jsonString);
        } catch (IOException e) {
            log.info("拦截器输出流异常" + e);
        }
    }

}
